package com.example.other.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.common.Message;

import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.example.authority.common.entity.Result;
import com.example.authority.common.utils.SecurityUtils;
import com.example.other.domain.Chat;
import com.example.other.domain.DTO.ChatDTO;
import com.example.other.domain.UsersInfo;
import com.example.other.service.ChatService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestController
public class ChatController {


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    ChatService chatService;
    Long totalToken=0L;
    @PostMapping("/chat")
    @ResponseBody
    public Result chat(@RequestBody ChatDTO chatDTO) throws NoApiKeyException, InputRequiredException {
        List<Message> l=new ArrayList<>();
        List<String> questions=chatDTO.getQuestions();
        List<String> answers=chatDTO.getAnswers();
        String question=questions.get(questions.size()-1);
        questions.remove(questions.size()-1);
        String prompt ="你是一个AI问诊机器人，你需要回答用户关于医疗方面的问题。用户可能会把自己的体检报告给你，" +
                "并要求你输出健康建议。请根据用户的问题和体检报告，回答用户的问题。";
        Message sysMessage=Message.builder().role(Role.SYSTEM.getValue())
                .content(prompt)
                .build();
        l.add(sysMessage);
        int len=questions.size();
        for(int i=0;i<len;i++){
            l.add(createMessage(Role.USER,questions.get(i)));
            l.add(createMessage(Role.ASSISTANT,answers.get(i)));
        }
        l.add(createMessage(Role.USER,question));
        Generation gen = new Generation();

        GenerationParam params = QwenParam.builder().model(Generation.Models.QWEN_MAX)
                .apiKey("sk-dcfff7f089594493a74571c64f25b7ea")
//                .prompt(prompt)
                .seed(1234)
                .topP(0.8)
                .resultFormat("message")
                .enableSearch(false)
                .maxTokens(1500)
                .temperature((float)0.85)
                .repetitionPenalty((float)1.0)
                .build();

        params.setMessages(l);
        GenerationResult result = gen.call(params);

        String ans=result.getOutput().getChoices().get(0).getMessage().getContent();
        questions.add(question);
        answers.add(ans);
        totalToken+=result.getUsage().getTotalTokens();

        Map<String, Object> map=Map.of("answer",ans,"totalToken",totalToken,"question",question);
        if(questions.size()>6){
            questions.remove(0);
        }
        if(answers.size()>6){
            answers.remove(0);
        }
        System.out.println(prompt);
        return Result.succ(map);
    }
    private static Message createMessage(Role role, String content) {
        return Message.builder().role(role.getValue()).content(content).build();
    }


    @GetMapping("chat/user")
    public Result chatUser() {
        List<UsersInfo> l= chatService.getChatedUsersByCosId(Math.toIntExact(SecurityUtils.getCurrentUser().getUser().getId()));
        return Result.succ(l);
    }
    @GetMapping("chat/user/{doctorId}")
    public Result chatDoctorUser(@PathVariable("doctorId") Integer doctorId) {
        Integer userId=Math.toIntExact(SecurityUtils.getCurrentUser().getUser().getId());
        List<Chat> l= chatService.getChatListByDoctorIdAndUserId(doctorId,userId);
        return Result.succ(l);
    }

}
